﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OleDb;

namespace Our.Umbraco.uDbCompare
{
    public class Db
    {
        /// <summary>
        /// Run a query against the db and return a datatable of results
        /// </summary>
        /// <param name="query"></param>
        /// <param name="useRemoteConnectionString"></param>
        /// <returns></returns>
        public static DataTable QueryDb(string query, bool useRemoteConnectionString)
        {
            return QueryDb(query, useRemoteConnectionString, null);
        }

        /// <summary>
        /// Run a query against the db and return a datatable of results
        /// </summary>
        /// <param name="query"></param>
        /// <param name="useRemoteConnectionString"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static DataTable QueryDb(string query, bool useRemoteConnectionString, OleDbParameter[] parameters)
        {
            DataTable dt = new DataTable();
            //using (OleDbConnection conn = new OleDbConnection(FormatConnectionString(connectionString)))
            using (OleDbConnection conn = new OleDbConnection(SessionVars.GetConnectionString(useRemoteConnectionString)))
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand(query, conn);
                if (parameters != null)
                    cmd.Parameters.AddRange(parameters);
                OleDbDataReader reader = cmd.ExecuteReader();

                dt.Load(reader);
            }
            foreach (DataColumn column in dt.Columns)
            {
                column.ReadOnly = false;
            }
            return dt;
        }

    }
}
